<script>
export default {
  name: 'DDropdown',
  model: {
    prop: 'visible',
    event: 'visibleChange'
  },
  props: {
    overlayClassName: {
      type: String
    },
    placement: {
      type: String,
      default: 'bottomLeft'
    },
    trigger: {
      type: Array,
      default: () => ['hover']
    },
    getPopupContainer: {
      type: Function
    },
    visible: {
      type: Boolean,
      default: null
    }
  },
  methods: {
    onVisibleChange(visible) {
      if (visible) {
        // https://www.notion.so/thingworks/BUG-f8db221f7e7245dc85029674902e9469
        setTimeout(() => {
          document.documentElement.addEventListener(
            'click',
            this.adapterStyle,
            {
              once: true
            }
          );
        }, 0);
      }

      const elements = document.getElementsByClassName('dropdown-relative');
      if (elements && Array.isArray(elements)) {
        elements.forEach(element => {
          element.style.overflow = visible ? 'hidden' : 'auto';
        });
      }
      this.$emit('visibleChange', visible);
    },
    adapterStyle() {
      const elements = document.getElementsByClassName('dropdown-relative');
      if (elements && Array.isArray(elements)) {
        elements.forEach(element => {
          element.style.overflow = 'auto';
        });
      }
    }
  },
  render() {
    const props = {
      overlayClassName: this.overlayClassName,
      placement: this.placement,
      trigger: this.trigger,
      getPopupContainer: this.getPopupContainer
    };

    if (this.visible !== null) {
      props.visible = this.visible;
    }

    const on = {
      visibleChange: this.onVisibleChange
    };

    return (
      <a-dropdown props={props} on={on} scopedSlots={this.$scopedSlots}>
        {this.$slots.default}
      </a-dropdown>
    );
  }
};
</script>

<style lang="scss">
.tw-dropdown {
  background: #ffffff;
  box-shadow: 0 1px 5px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #eeeeee;
}
.tw-dropdown-menu-item {
  &:hover {
    background-color: #eff4fe !important;
  }
}
.tw-dropdown-menu-submenu-title {
  &:hover {
    background-color: #eff4fe !important;
  }
}
</style>
